<?php defined('SYSPATH') or die('No direct script access.');

class Controller_User extends Controller_User_Template {

	public function action_index()
	{
	}

	/*
	public function action_register()
	{
		if($_POST)
		{
			$user = ORM::factory('user');
			$user->values($_POST);			
			$user->save();
			
			$user->add('roles', ORM::factory('role')->where('name', '=', 'login')->find());
		}
		else
		{
			$view = new View('user/register');		
			$this->response->body($view);
		}
	}
	
	*/
	
	public function action_register()
	{
		$view = View::factory('user/register');
		$view->set('values', $_POST);
		$view->bind('errors', $errors);
	
		if($_POST) {
			$user = ORM::factory('user');
			$user->values($_POST);
				
			$extra_rules = ORM::factory('user')
			->get_password_validation($_POST);
				
			try {
				$user->save($extra_rules);
				$user->add('roles', ORM::factory('role')->where('name', '=', 'login')->find());
				$this->request->redirect('admin/users');
			}
			catch (ORM_Validation_Exception $e) {
				$errors = $e->errors('model');
			}
		}
		$this->template->title = __('Register New User');
		$this->template->content = $view;
	}
	
	public function action_login()
	{
		$view = new View('user/login');
		$view->bind('error', $error);
		
		if($this->request->post())
		{
			$username = $this->request->post('username');
			$password = $this->request->post('password');			
			$success = Auth::instance()->login($username,$password, FALSE);
			
			if($success)
			{
				/*
				if($url = Session::instance()->get('redirect_url')) {
					$this->request->redirect($url);
				}
				*/
				if(Auth::instance()->get_user()->has('roles', ORM::factory('role', 2))):
					$this->request->redirect('admin/');
				endif;
				$this->request->redirect($this->request->referrer());
			}
			else {
				$error = 'Failed to log in.';	
			}
		}
		
		$this->template->content = $view;
		
	}
	
	public function action_logout()
	{
		Auth::instance()->logout();
		$this->request->redirect('');
	}
	
	public function action_profile()
	{
	}
	
}